import base64
import cookielib
import json
import urllib
import urllib2
import re
import binascii
import rsa

__author__ = 'weijinshi'


class WeiboLogin:
    def __init__(self, username, pwd, enableProxy = False):
        self.__username = username
        self.__pwd = pwd
        self.__enable_proxy = enableProxy
        self.__pre_login_url = 'http://login.sina.com.cn/sso/prelogin.php?entry=weibo&callback=sinaSSOController.preloginCallBack&su=&rsakt=mod&client=ssologin.js(v1.4.11)&_=1398508518009'
        self.__login_url = 'http://login.sina.com.cn/sso/login.php?client=ssologin.js(v1.4.11)'
        self.__post_header = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; rv:24.0) Gecko/20100101 Firefox/24.0'}

    def login(self):
        self.__enable_cookie()
        servertime, nonce, pubkey, rsakv = self.__get_pre_login_data()
        post_data = self.__encode_post_data(servertime, nonce, pubkey, rsakv)

        req = urllib2.Request(self.__login_url, post_data, self.__post_header)
        text = urllib2.urlopen(req).read()
        try:
            p = re.compile('location\.replace\([\'"](.*?)[\'"]\)')
            real_login_url = p.search(text).group(1)
            urllib2.urlopen(real_login_url)
        except Exception, e:
            print 'Error: Login error! ', e
            return False

        print 'Login success!'
        return True

    def __enable_cookie(self):
        cookie_jar = cookielib.LWPCookieJar()
        cookie_support = urllib2.HTTPCookieProcessor(cookie_jar)
        if self.__enable_proxy:
            proxy_support = urllib2.ProxyHandler({'http': 'http://xxxxx.pac'})
            opener = urllib2.build_opener(proxy_support, cookie_support, urllib2.HTTPHandler)
            print "Proxy enabled"
        else:
            opener = urllib2.build_opener(cookie_support, urllib2.HTTPHandler)
        urllib2.install_opener(opener)

    def __get_pre_login_data(self):
        server_data = urllib2.urlopen(self.__pre_login_url).read()
        try:
            p = re.compile('\((.*)\)')
            json_data = p.search(server_data).group(1)
            data = json.loads(json_data)
            servertime = str(data['servertime'])
            nonce = data['nonce']
            pubkey = data['pubkey']
            rsakv = data['rsakv']
            return servertime, nonce, pubkey, rsakv
        except Exception, e:
            print 'Error: Get pre login data error! ', e
            return None

    def __encode_post_data(self, servertime, nonce, pubkey, rsakv):
        temp_username = urllib.quote(self.__username)
        encoded_username = base64.encodestring(temp_username)[:-1]

        rsa_pk = int(pubkey, 16)
        key = rsa.PublicKey(rsa_pk, 65537)
        message = str(servertime) + '\t' + str(nonce) + '\n' + str(self.__pwd)
        temp_pwd = rsa.encrypt(message, key)
        encoded_pwd = binascii.b2a_hex(temp_pwd)

        post_param = {
            'entry': 'weibo',
            'gateway': '1',
            'from': '',
            'savestate': '7',
            'userticket': '1',
            'ssosimplelogin': '1',
            'vsnf': '1',
            'vsnval': '',
            'su': encoded_username,
            'service': 'miniblog',
            'servertime': servertime,
            'nonce': nonce,
            'pwencode': 'rsa2',
            'sp': encoded_pwd,
            'encoding': 'UTF-8',
            'prelt': '115',
            'rsakv': rsakv,
            'url': 'http://weibo.com/ajaxlogin.php?framelogin=1&callback=parent.sinaSSOController.feedBackUrlCallBack',
            'returntype': 'META'
        }
        post_data = urllib.urlencode(post_param)
        return post_data